/**
 * @author mamat-dev
 */
package com.googlecode.explorecode.mamat.sendimage;

import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;

public class CameraMIDlet extends MIDlet {
	private CameraForm cameraSave = null;
	private DisplayImage displayImage = null;
	public CameraMIDlet() {
        
	}
	/*
	 * startApp()
	 * starts MIDlet dan generate cameraSave, displayImage, database
	 *
	 **/
	public void startApp() {
		Displayable current = Display.getDisplay(this).getCurrent();
		if (current == null) {
			//pertaman kali ketika di call
			cameraSave = new CameraForm(this);
			displayImage = new DisplayImage(this);
			Display.getDisplay(this).setCurrent(cameraSave);
			cameraSave.start();
		} else {
			//mengembalikan ketika di-pauseApp
			if (current == cameraSave) {
				cameraSave.start();
			}
			Display.getDisplay(this).setCurrent(current);
		}
	}
	public void pauseApp() {
		if (Display.getDisplay(this).getCurrent() == cameraSave) {
			cameraSave.stop();
		}
	}
	public void destroyApp(boolean unconditional) {
		if (Display.getDisplay(this).getCurrent() == cameraSave) {
			cameraSave.stop();
		}
	}
	private void exitRequested() {
		destroyApp(false);
		notifyDestroyed();
	}
	void cameraFormExit() {
		exitRequested();
	}
	/**
	 * restart camera lagi
	 *
	 */
	void displayCanvasBack() {
		Display.getDisplay(this).setCurrent(cameraSave);
		cameraSave.start();
	}
	/**
	 *	byte[] image harus dikirim ke server
	 *
	 **/
	void buildHTTPConnection(byte[] byteImage) {
		displayImage.setImage(byteImage);
		Display.getDisplay(this).setCurrent(displayImage);
		HttpConnection hc = null;
		OutputStream out = null;
		try {
			// encode image data menggunakan Base64 algorithm
			String stringImage = Base64.encode(byteImage);
			// URL of the Sevlet
			String url = new String(
			"http://localhost:81/WSendImage/imageserv");
			// membuat HTTPConnection
			hc = (HttpConnection) Connector.open(url);
			// Modifikasi header hasil dari http request
			hc.setRequestMethod(HttpConnection.POST);
			// mempersiapkan output stream hasil dari HttpConnection
            out = hc.openOutputStream();
			out.write(stringImage.getBytes());			
		} catch (IOException ioe) {
			StringItem stringItem = new StringItem(null, ioe.toString());
		} finally {
			try {
				if (out != null)
					out.close();
				if (hc != null)
					hc.close();
			} catch (IOException ioe) {
			}
		}
	}

	/**
	 *	stop kamera, tampilkan image dan kirim image ke server
	 **/
	void transmitImage(byte[] image) {
		cameraSave.stop();
		Display.getDisplay(this).setCurrent(displayImage);
		buildHTTPConnection(image);
	}
}